package solution1.demo1201.demo2.tool;

import java.io.*;

public class BinaryTool {

    public static byte[] toBytes(Object object) {
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object fromBytes(byte[] bytes) {
        Object result = null;
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                result = objectInputStream.readObject();
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
